<template>
  <div class="mappanel-container">
    <h1>地图服务</h1>
    <el-divider></el-divider>
    <div>
      <div style="margin: 20px 0;">
        <span>地理/逆地理编码</span>
      </div>
      <div style="margin: 20px 0;">
        <el-input type="text" autosize placeholder="请输入中文地址" v-model="textarea1">
          <template slot="prepend">地址</template>
          <el-button slot="append" icon="el-icon-search" @click="send"></el-button>
        </el-input>
        <el-collapse-transition>
          <el-input type="text" autosize readonly v-model="textarea2" v-show="show1">
            <template slot="prepend">经纬</template>
          </el-input>
        </el-collapse-transition>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
      <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
      </el-table>
    </div>
    <el-divider>
    </el-divider>
    <div>
      <el-upload
        ref="upload"
        class="upload-demo"
        name="data"
        multiple="false"
        :action="action_url"
        :auto-upload="false"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :http-request="clickup"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
      </el-upload>
      <el-button @click="downloads">下载</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { send, sendCB, download } from '@/views/mappanel/mappanel'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import axios from 'axios'

export default {
  name: 'MapPanel',
  components: { UploadExcelComponent },
  props: {},
  data() {
    return {
      // 输入框
      textarea1: '',
      textarea2: '经纬度',

      // 动画控制
      show1: false,

      // 表格数据变量
      tableData: [],
      tableHeader: [],

      // 上传参数
      action_url: process.env.VUE_APP_BASE_API + '/vue-admin-template/user/uploads'
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    // 发送
    send() {
      if (this.show1) { this.show1 = false }
      return new Promise((resolve, reject) => {
        console.log('进入发送函数')
        send({ addr: this.textarea1 }).then(response => {
          const data = response
          console.log(data)
          this.textarea2 = sendCB(data)
          this.show1 = true
          resolve()
        }).catch(error => {
          console.log('发送失败' + error)
          this.show1 = false
          reject(error)
        })
      })
    },

    // // 加载excel前
    // beforeUpload(file) {
    //   const isLimit = file.size / 1024 / 1024 < 20
    //
    //   if (isLimit) {
    //     return true
    //   }
    //
    //   this.message({
    //     message: '请勿上传大于20M的文件.',
    //     type: 'warning'
    //   })
    //   return false
    // },
    //
    // // 加载成功
    // handleSuccess({ results, header }) {
    //   this.tableData = results
    //   this.tableHeader = header
    // },

    // upload原生方法
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    submitUpload() {
      console.log('上传文件!')
      this.$refs.upload.submit()
    },
    handleSuccess(res, rawFile) {
      // res与rawFile是commit成功后，后端返回的response响应
      console.log(res)
      // // 构造BLOB
      // const blob = new Blob([res])
      // save2file(blob, 'demo_download.xlsx')
    },
    downloads() {
      return new Promise((resolve, reject) => {
        // console.log(`${url} 请求数据，参数=>`, JSON.stringify(options))
        // axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
        axios({
          method: 'post',
          url: process.env.VUE_APP_BASE_API + '/vue-admin-template/user/mapservice/download', // 请求地址
          data: 'options', // 参数
          responseType: 'blob' // 表明返回服务器返回的数据类型
        }).then(
          response => {
            // console.log("下载响应",response)
            resolve(response.data)
            const blob = new Blob([response.data], {
              type: 'application/vnd.ms-excel'
            })
            // console.log(blob)
            // let fileName = Date.parse(new Date()) + '.xlsx'
            // 切割出文件名
            const fileNameEncode = response.headers['content-disposition'].split('filename=')[1]
            // 解码
            const fileName = decodeURIComponent(fileNameEncode)
            // console.log("fileName",fileName)
            if (window.navigator.msSaveOrOpenBlob) {
              // console.log(2)
              navigator.msSaveBlob(blob, fileName)
            } else {
              // console.log(3)
              var link = document.createElement('a')
              link.href = window.URL.createObjectURL(blob)
              link.download = fileName
              link.click()
              // 释放内存
              window.URL.revokeObjectURL(link.href)
            }
          },
          err => {
            reject(err)
          }
        )
      })
    },
    // 自定义的上传文件方法
    clickup(option) {
      console.log(option)

      return new Promise((resolve, reject) => {
        // console.log(`${url} 请求数据，参数=>`, JSON.stringify(options))
        // axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
        const formData = new FormData()
        formData.append(option.filename, option.file, option.file.name)
        axios({
          method: 'post',
          url: process.env.VUE_APP_BASE_API + '/vue-admin-template/user/mapservice/download', // 请求地址
          data: formData, // 参数
          responseType: 'blob' // 表明返回服务器返回的数据类型
        }).then(
          response => {
            // console.log("下载响应",response)
            resolve(response.data)
            const blob = new Blob([response.data], {
              type: 'application/vnd.ms-excel'
            })
            // console.log(blob)
            // let fileName = Date.parse(new Date()) + '.xlsx'
            // 切割出文件名
            const fileNameEncode = response.headers['content-disposition'].split('filename=')[1]
            // 解码
            const fileName = decodeURIComponent(fileNameEncode)
            // console.log("fileName",fileName)
            if (window.navigator.msSaveOrOpenBlob) {
              // console.log(2)
              navigator.msSaveBlob(blob, fileName)
            } else {
              // console.log(3)
              var link = document.createElement('a')
              link.href = window.URL.createObjectURL(blob)
              link.download = fileName
              link.click()
              // 释放内存
              window.URL.revokeObjectURL(link.href)
            }
          },
          err => {
            reject(err)
          }
        )
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mappanel {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  background-color: #409EFF;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
</style>
